//
//  BlingPhoneView.m
//  location
//
//  Created by Dongxiang Xu on 2025/10/24.
//

#import "BlingPhoneView.h"

@interface BlingPhoneView ()<UITextFieldDelegate>

@property (nonatomic,strong) UIView *infoView;
@property (nonatomic,strong) UIView *inputView;
@property (nonatomic,strong) UITextField *textField;
@property (nonatomic,strong) UITextField *exTextField;
@property (nonatomic,strong) UIButton *next;
@property (nonatomic,strong) UILabel *extraNum;
@property (nonatomic,strong) UIScrollView *scrollView;
@property (nonatomic,strong) UIButton *timeButton;
@property (nonatomic,strong) UIButton *blingButton;
@property (nonatomic,strong) NSTimer *timer;

@end

@implementation BlingPhoneView

- (instancetype)initWithFrame:(CGRect)frame
                IsChangePhone:(BOOL)isChangePhone
{
    self = [super initWithFrame:frame];
    if (self) {
        
        
        
        _infoView = [[UIView alloc] initWithFrame:CGRectMake(12, SCREEN_HEIGHT, SCREEN_WIDTH-24, 360)];
        _infoView.backgroundColor = RealWhiteColor;
        _infoView.layer.masksToBounds = YES;
        [_infoView.layer setCornerRadius:40];
        [self addSubview:_infoView];
        
        _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, _infoView.width, _infoView.height)];
        _scrollView.contentSize = CGSizeMake(_infoView.width*2, 0);
        _scrollView.scrollEnabled = NO;
        [_infoView addSubview:_scrollView];
        
        UIButton *close = [[UIButton alloc] initWithFrame:CGRectMake(_infoView.width-46, 16, 30, 30)];
        [close setImage:[UIImage imageNamed:@"map_close"] forState:UIControlStateNormal];
        [_infoView addSubview:close];
        [[close rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            [UIView animateWithDuration:0.3 animations:^{
                self.infoView.y = SCREEN_HEIGHT;
                self.backgroundColor = [RealBlackColor colorWithAlphaComponent:0];
            } completion:^(BOOL finished) {
                [self removeFromSuperview];
            }];
        }];
        
        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(0, 78, _infoView.width, 28)];
        title.textAlignment = NSTextAlignmentCenter;
        if (isChangePhone) {
            title.text = @"输入换绑手机号";
        }else{
            title.text = @"输入绑定手机号";
        }
        title.textColor = BlackColor;
        title.font = MEDIUM_FONT(20);
        [_scrollView addSubview:title];
        
        UILabel *code = [[UILabel alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-220)/2, title.maxY+58, 36, 56)];
        code.textColor = GraryHeavyLightColor;
        code.font = RUBIK_BOLD_FONT(18);
        code.text = @"+86";
        [_scrollView addSubview:code];
        
        _inputView = [[UIView alloc] initWithFrame:CGRectMake(code.maxX+10, title.maxY+58, 174, 56)];
        _inputView.backgroundColor = LightBGColor;
        _inputView.layer.masksToBounds = YES;
        [_inputView.layer setBorderWidth:1];
        [_inputView.layer setCornerRadius:16];
        [_scrollView addSubview:_inputView];
        
        _textField = [[UITextField alloc] initWithFrame:CGRectMake(12, 0, _inputView.width-24, _inputView.height)];
        _textField.keyboardType = UIKeyboardTypeNumberPad;
        [_textField becomeFirstResponder];
        _textField.textAlignment = NSTextAlignmentCenter;
        _textField.textColor = NormalMainColor;
        _textField.tintColor = NormalMainColor;
        _textField.placeholder = @"输入手机号";
        _textField.font = RUBIK_BOLD_FONT(18);
        _textField.delegate = self;
        [_textField addTarget:self action:@selector(textChangeEvent:) forControlEvents:UIControlEventEditingChanged];
        [_inputView addSubview:_textField];
        
        _next = [[UIButton alloc] initWithFrame:CGRectMake(20, _inputView.maxY+56, _infoView.width-40, 54)];
        _next.backgroundColor = LightBGColor;
        _next.layer.masksToBounds = YES;
        [_next.layer setCornerRadius:27];
        [_next setTitle:@"下一步" forState:UIControlStateNormal];
        [_next setTitleColor:GraryTooHeavyColor forState:UIControlStateNormal];
        _next.userInteractionEnabled = NO;
        [_scrollView addSubview:_next];
        [[_next rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            if (isChangePhone) {
                NSMutableDictionary *param = [NSMutableDictionary dictionary];
                [param setValue:self.textField.text forKey:@"newPhonenumber"];
                CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
                [manager encryptedPOST:@"/auth/rebind/new/send"
                parameters:param
                success:^(NSDictionary *responseObject) {
                    if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
                        self.extraNum.text = [NSString stringWithFormat:@"为了账户安全，需验证尾号 %@ 手机号码",[self.textField.text substringFromIndex:7]];
                        [self.scrollView setContentOffset:CGPointMake(self.infoView.width, 0) animated:YES];
                        [self.exTextField becomeFirstResponder];
                        [self initTimer];
                    }else{
                        [[HCToast shareInstance] showToast:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
                    }
                }
                failure:^(NSError *aError) {
                    
                }];
            }else{
                NSMutableDictionary *param = [NSMutableDictionary dictionary];
                [param setValue:self.textField.text forKey:@"phonenumber"];
                CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
                [manager encryptedPOST:@"/auth/smslogin"
                parameters:param
                success:^(NSDictionary *responseObject) {
                    if ([responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
                        self.extraNum.text = [NSString stringWithFormat:@"为了账户安全，需验证尾号 %@ 手机号码",[self.textField.text substringFromIndex:7]];
                        [self.scrollView setContentOffset:CGPointMake(self.infoView.width, 0) animated:YES];
                        [self.exTextField becomeFirstResponder];
                        [self initTimer];
                    }else{
                        [[HCToast shareInstance] showToast:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
                    }
                }
                failure:^(NSError *aError) {
                    
                }];
            }
        }];
                
        {
            
            UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(_infoView.width, 78, _infoView.width, 28)];
            title.textAlignment = NSTextAlignmentCenter;
            title.text = @"输入验证码";
            title.textColor = BlackColor;
            title.font = MEDIUM_FONT(20);
            [_scrollView addSubview:title];
            
            _extraNum = [[UILabel alloc] initWithFrame:CGRectMake(_infoView.width, title.maxY+6, _infoView.width, 24)];
            _extraNum.textAlignment = NSTextAlignmentCenter;
            _extraNum.textColor = GraryTooHeavyColor;
            _extraNum.font = DEFAULT_FONT(13);
            [_scrollView addSubview:_extraNum];
            
            _exTextField = [[UITextField alloc] initWithFrame:CGRectMake(2*_infoView.width, 0, 100, 10)];
            _exTextField.keyboardType = UIKeyboardTypeNumberPad;

            [_exTextField addTarget:self action:@selector(exTextChangeEvent:) forControlEvents:UIControlEventEditingChanged];
            [_scrollView addSubview:_exTextField];
            
            for (int i=0; i<4; i++) {
                UIButton *view = [[UIButton alloc] initWithFrame:CGRectMake(_infoView.width+(_infoView.width-198)/2+i*52, CGRectGetMaxY(_extraNum.frame)+28, 42, 56)];
                view.layer.masksToBounds = YES;
                if (i==0) {
                    view.backgroundColor = NormalMainColor;
                }else{
                    view.backgroundColor = LightBGColor;
                }
                [view.layer setCornerRadius:16];
                [view setTitleColor:RealBlackColor forState:UIControlStateNormal];
                [view.titleLabel setFont:RUBIK_BOLD_FONT(24)];
                view.tag = 100 + i;
                [self.scrollView addSubview:view];
                [[view rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                    [self.exTextField becomeFirstResponder];
                }];
            }
            
            _timeButton = [[UIButton alloc] initWithFrame:CGRectMake(_infoView.width+30, CGRectGetMaxY(_extraNum.frame)+94, _infoView.width-60, 18)];
            [_timeButton setTitleColor:GraryHeavyLightColor forState:UIControlStateNormal];
            [_timeButton.titleLabel setFont:DEFAULT_FONT(13)];
            _timeButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
            [self.timeButton setTitle:@"60秒后可以请求新验证码" forState:UIControlStateNormal];
            [self.scrollView addSubview:_timeButton];
            [[_timeButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                if ([self.timeButton.titleLabel.text containsString:@"重新发送"]) {
                    [self initTimer];
                }
            }];
            
            _blingButton = [[UIButton alloc] initWithFrame:CGRectMake(_infoView.width+20, _timeButton.maxY+28, _infoView.width-40, 54)];
            _blingButton.layer.masksToBounds = YES;
            [_blingButton.layer setCornerRadius:27];
            if (isChangePhone) {
                [_blingButton setTitle:@"更换绑定" forState:UIControlStateNormal];
            }else{
                [_blingButton setTitle:@"绑定" forState:UIControlStateNormal];
            }
            [_blingButton.titleLabel setFont:MEDIUM_FONT(16)];
            _blingButton.backgroundColor = LightBGColor;
            [_blingButton setTitleColor:GraryTooHeavyColor forState:UIControlStateNormal];
            _blingButton.userInteractionEnabled = NO;
            [_scrollView addSubview:_blingButton];
            [[_blingButton rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                [self loginEvent];
            }];
        }
        
        UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        [self insertSubview:bgView atIndex:0];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] init];
        [[tap rac_gestureSignal] subscribeNext:^(id x) {
            [UIView animateWithDuration:0.3 animations:^{
                self.infoView.y = SCREEN_HEIGHT;
                self.backgroundColor = [RealBlackColor colorWithAlphaComponent:0];
            } completion:^(BOOL finished) {
                [self removeFromSuperview];
            }];
        }];
        [bgView addGestureRecognizer:tap];
        
        [UIView animateWithDuration:0.3 animations:^{
            self.infoView.y = (SCREEN_HEIGHT-self.infoView.height)/2-56;
            self.backgroundColor = [RealBlackColor colorWithAlphaComponent:0.4];
        }];
    }
    return self;
}

- (void)initTimer
{
    [self.timer invalidate];
    self.timer = nil;
    __block NSInteger seconds = 60;
    self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 repeats:YES block:^(NSTimer * _Nonnull timer) {
        seconds = seconds-1;
        if (seconds<=0) {
            [timer invalidate];
            timer = nil;
            [self.timeButton setImage:[UIImage imageNamed:@"loging"] forState:UIControlStateNormal];
            [self.timeButton setTitle:@" 重新发送" forState:UIControlStateNormal];
            [self.timeButton setTitleColor:GraryHeavyLightColor forState:UIControlStateNormal];
            [self.timeButton.titleLabel setFont:REAL_MEDIUM_FONT(14)];
        }else{
            [self.timeButton setImage:nil forState:UIControlStateNormal];
            [self.timeButton setTitleColor:GraryTooHeavyColor forState:UIControlStateNormal];
            [self.timeButton setTitle:[NSString stringWithFormat:@"%ld秒后可以请求新验证码",(long)seconds] forState:UIControlStateNormal];
            [self.timeButton.titleLabel setFont:DEFAULT_FONT(13)];
        }
    }];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSDefaultRunLoopMode];
}

- (void)textChangeEvent:(UITextField *)textField
{
    if (textField.text.length>=11) {
        textField.text = [textField.text substringToIndex:11];
        [_next setTitleColor:RealWhiteColor forState:UIControlStateNormal];
        _next.backgroundColor = NormalMainColor;
        _next.userInteractionEnabled = YES;
    }else{
        [_next setTitleColor:GraryTooHeavyColor forState:UIControlStateNormal];
        _next.backgroundColor = LightBGColor;
        _next.userInteractionEnabled = NO;
    }
}

-(void)exTextChangeEvent:(UITextField *)textField
{
   if (textField.text.length>=4) {
       textField.text = [textField.text substringToIndex:4];
       [((UIButton *)[self viewWithTag:103]) setTitle:[textField.text substringWithRange:NSMakeRange(3, 1)] forState:UIControlStateNormal];
       [self viewWithTag:103].backgroundColor = NormalMainColor;
       [((UIButton *)[self viewWithTag:103]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
       
       [((UIButton *)[self viewWithTag:102]) setTitle:[textField.text substringWithRange:NSMakeRange(2, 1)] forState:UIControlStateNormal];
       [self viewWithTag:102].backgroundColor = LightBGColor;
       [((UIButton *)[self viewWithTag:102]) setTitleColor:NormalMainColor forState:UIControlStateNormal];
       
       [((UIButton *)[self viewWithTag:101]) setTitle:[textField.text substringWithRange:NSMakeRange(1, 1)] forState:UIControlStateNormal];
       [self viewWithTag:101].backgroundColor = LightBGColor;
       [((UIButton *)[self viewWithTag:101]) setTitleColor:NormalMainColor forState:UIControlStateNormal];
       
       [((UIButton *)[self viewWithTag:100]) setTitle:[textField.text substringWithRange:NSMakeRange(0, 1)] forState:UIControlStateNormal];
       [self viewWithTag:100].backgroundColor = LightBGColor;
       [((UIButton *)[self viewWithTag:100]) setTitleColor:NormalMainColor forState:UIControlStateNormal];
       
       _blingButton.backgroundColor = NormalMainColor;
       [_blingButton setTitleColor:RealWhiteColor forState:UIControlStateNormal];
       _blingButton.userInteractionEnabled = YES;
       
       [self loginEvent];
   }else if (textField.text.length == 3){
       [((UIButton *)[self viewWithTag:103]) setTitle:@"" forState:UIControlStateNormal];
       [self viewWithTag:103].backgroundColor = LightBGColor;
       [((UIButton *)[self viewWithTag:103]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
       
       [((UIButton *)[self viewWithTag:102]) setTitle:[textField.text substringWithRange:NSMakeRange(2, 1)] forState:UIControlStateNormal];
       [self viewWithTag:102].backgroundColor = NormalMainColor;
       [((UIButton *)[self viewWithTag:102]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
       
       [((UIButton *)[self viewWithTag:101]) setTitle:[textField.text substringWithRange:NSMakeRange(1, 1)] forState:UIControlStateNormal];
       [self viewWithTag:101].backgroundColor = LightBGColor;
       [((UIButton *)[self viewWithTag:101]) setTitleColor:NormalMainColor forState:UIControlStateNormal];
       
       [((UIButton *)[self viewWithTag:100]) setTitle:[textField.text substringWithRange:NSMakeRange(0, 1)] forState:UIControlStateNormal];
       [self viewWithTag:100].backgroundColor = LightBGColor;
       [((UIButton *)[self viewWithTag:100]) setTitleColor:NormalMainColor forState:UIControlStateNormal];
       
       _blingButton.backgroundColor = LightBGColor;
       [_blingButton setTitleColor:GraryTooHeavyColor forState:UIControlStateNormal];
       _blingButton.userInteractionEnabled = NO;
   }else if (textField.text.length == 2){
       [((UIButton *)[self viewWithTag:103]) setTitle:@"" forState:UIControlStateNormal];
       [self viewWithTag:103].backgroundColor = LightBGColor;
       [((UIButton *)[self viewWithTag:103]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
       
       [((UIButton *)[self viewWithTag:102]) setTitle:@"" forState:UIControlStateNormal];
       [self viewWithTag:102].backgroundColor = LightBGColor;
       [((UIButton *)[self viewWithTag:102]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
       
       [((UIButton *)[self viewWithTag:101]) setTitle:[textField.text substringWithRange:NSMakeRange(1, 1)] forState:UIControlStateNormal];
       [self viewWithTag:101].backgroundColor = NormalMainColor;
       [((UIButton *)[self viewWithTag:101]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
       
       [((UIButton *)[self viewWithTag:100]) setTitle:[textField.text substringWithRange:NSMakeRange(0, 1)] forState:UIControlStateNormal];
       [self viewWithTag:100].backgroundColor = LightBGColor;
       [((UIButton *)[self viewWithTag:100]) setTitleColor:NormalMainColor forState:UIControlStateNormal];
       
       _blingButton.backgroundColor = LightBGColor;
       [_blingButton setTitleColor:GraryTooHeavyColor forState:UIControlStateNormal];
       _blingButton.userInteractionEnabled = NO;
   }else if (textField.text.length == 1){
       [((UIButton *)[self viewWithTag:103]) setTitle:@"" forState:UIControlStateNormal];
       [self viewWithTag:103].backgroundColor = LightBGColor;
       [((UIButton *)[self viewWithTag:103]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
       
       [((UIButton *)[self viewWithTag:102]) setTitle:@"" forState:UIControlStateNormal];
       [self viewWithTag:102].backgroundColor = LightBGColor;
       [((UIButton *)[self viewWithTag:102]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
       
       [((UIButton *)[self viewWithTag:101]) setTitle:@"" forState:UIControlStateNormal];
       [self viewWithTag:101].backgroundColor = LightBGColor;
       [((UIButton *)[self viewWithTag:101]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
       
       [((UIButton *)[self viewWithTag:100]) setTitle:[textField.text substringWithRange:NSMakeRange(0, 1)] forState:UIControlStateNormal];
       [self viewWithTag:100].backgroundColor = NormalMainColor;
       [((UIButton *)[self viewWithTag:100]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
       
       _blingButton.backgroundColor = LightBGColor;
       [_blingButton setTitleColor:GraryTooHeavyColor forState:UIControlStateNormal];
       _blingButton.userInteractionEnabled = NO;
   }else{
       [((UIButton *)[self viewWithTag:103]) setTitle:@"" forState:UIControlStateNormal];
       [self viewWithTag:103].backgroundColor = LightBGColor;
       [((UIButton *)[self viewWithTag:103]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
       
       [((UIButton *)[self viewWithTag:102]) setTitle:@"" forState:UIControlStateNormal];
       [self viewWithTag:102].backgroundColor = LightBGColor;
       [((UIButton *)[self viewWithTag:102]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
       
       [((UIButton *)[self viewWithTag:101]) setTitle:@"" forState:UIControlStateNormal];
       [self viewWithTag:101].backgroundColor = LightBGColor;
       [((UIButton *)[self viewWithTag:101]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
       
       [((UIButton *)[self viewWithTag:100]) setTitle:@"" forState:UIControlStateNormal];
       [self viewWithTag:100].backgroundColor = NormalMainColor;
       [((UIButton *)[self viewWithTag:100]) setTitleColor:RealWhiteColor forState:UIControlStateNormal];
       
       _blingButton.backgroundColor = LightBGColor;
       [_blingButton setTitleColor:GraryTooHeavyColor forState:UIControlStateNormal];
       _blingButton.userInteractionEnabled = NO;
   }
}

- (void)loginEvent
{
    if (_exTextField.text.length==4) {
        
        if (_blingButton.titleLabel.text.length==4) {
            NSMutableDictionary *param = [NSMutableDictionary dictionary];
            [param setValue:self.exTextField.text forKey:@"code"];
            [param setValue:self.textField.text forKey:@"newPhonenumber"];
            CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
            [manager encryptedPOST:@"/auth/rebind/confirm"
            parameters:param
            success:^(NSDictionary *responseObject) {
                if ([responseObject[@"code"] integerValue]==200) {
                    if (self.BlingPhoneSuccessBlock) {
                        self.BlingPhoneSuccessBlock(self.textField.text);
                    }
                    [[HCToast shareInstance] showToast:@"换绑成功"];
                    [UIView animateWithDuration:0.3 animations:^{
                        self.infoView.y = SCREEN_HEIGHT;
                        self.backgroundColor = [RealBlackColor colorWithAlphaComponent:0];
                    } completion:^(BOOL finished) {
                        [self removeFromSuperview];
                    }];
                }else{
                    [[HCToast shareInstance] showToast:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
                }
                [self.exTextField setEnabled:YES];
            }
            failure:^(NSError *aError) {
                [self.exTextField setEnabled:YES];
            }];
        }else{
            NSMutableDictionary *param = [NSMutableDictionary dictionary];
            [param setValue:self.exTextField.text forKey:@"code"];
            [param setValue:self.textField.text forKey:@"phonenumber"];
            CryptoHTTPKit *manager = [[CryptoHTTPKit alloc] init];
            [manager encryptedPOST:@"/auth/bindphone"
            parameters:param
            success:^(NSDictionary *responseObject) {
                if ([responseObject[@"code"] integerValue]==200) {
                    if (self.BlingPhoneSuccessBlock) {
                        self.BlingPhoneSuccessBlock(self.textField.text);
                    }
                    [[HCToast shareInstance] showToast:@"绑定成功"];
                    [UIView animateWithDuration:0.3 animations:^{
                        self.infoView.y = SCREEN_HEIGHT;
                        self.backgroundColor = [RealBlackColor colorWithAlphaComponent:0];
                    } completion:^(BOOL finished) {
                        [self removeFromSuperview];
                    }];
                }else{
                    [[HCToast shareInstance] showToast:[NSString stringWithFormat:@"%@",responseObject[@"msg"]]];
                }
                [self.exTextField setEnabled:YES];
            }
            failure:^(NSError *aError) {
                [self.exTextField setEnabled:YES];
            }];
        }
    }
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    [_inputView.layer setBorderColor:NormalMainColor.CGColor];
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    [_inputView.layer setBorderColor:[UIColor clearColor].CGColor];
}

@end
